﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace 控件调整.Common
{
    public class PasswordTools
    {
        public static string GetPassword(DependencyObject obj)
        {
            return (string)obj.GetValue(PasswordProperty);
        }

        public static void SetPassword(DependencyObject obj, string value)
        {
            obj.SetValue(PasswordProperty, value);
        }

        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordTools), defaultMetadata: new PropertyMetadata("",OnPasswordChanged));

        static bool isUpdating = false;
        private static void OnPasswordChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (isUpdating) return;
            PasswordBox? pd = d as PasswordBox;
            pd.PasswordChanged -= Pd_PasswordChanged;
            
            if (e.NewValue != null)
            {
                pd.Password = e.NewValue.ToString();
            }
            pd.PasswordChanged += Pd_PasswordChanged;
        }

        private static void Pd_PasswordChanged(object sender, RoutedEventArgs e)
        {
            isUpdating = true;

            PasswordBox? pd = sender as PasswordBox;
            if(pd != null)
            {
                SetPassword(pd, pd.Password.Trim());
            }
            isUpdating = false;
        }



        public static bool GetAttach(DependencyObject obj)
        {
            return (bool)obj.GetValue(AttachProperty);
        }

        public static void SetAttach(DependencyObject obj, bool value)
        {
            obj.SetValue(AttachProperty, value);
        }

        public static readonly DependencyProperty AttachProperty =
            DependencyProperty.RegisterAttached("Attach", typeof(bool), typeof(PasswordTools), new PropertyMetadata(false,OnAttachChanged));

        private static void OnAttachChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            PasswordBox? pd = d as PasswordBox;
            if (pd != null)
            {
                pd.PasswordChanged += Pd_PasswordChanged;
            }
        }
    }
}
